import jsonp from 'jsonp';
import ajax from './ajax';
import getCityAdcode from './weather/getCityCode';

export const loginRequest = (username, password) =>
  ajax(
    'http://localhost:3000/api1/login',
    { username, password },
    'POST',
    'x-www-form-urlencoded'
  );

export const addUserRequest = (user) =>
  ajax(
    'http://localhost:3000/api1/manage/add',
    user,
    'POST',
    'x-www-form-urlencoded'
  );

export const findCategoryByIdRequest = (id) =>
  ajax(`http://159.75.128.32:5000/api/category/list/${id}`, {}, 'GET');

export const real_findCategoryByIdRequest = (id) =>
  ajax(
    `http://159.75.128.32:5000/api/category/findCategoryById/${id}`,
    {},
    'GET'
  );

export const addCategoryRequest = (categoryData) =>
  ajax(
    'http://159.75.128.32:5000/api/category/add',
    categoryData,
    'POST',
    'json'
  );

export const updateCategoryRequest = (categoryData) =>
  ajax(
    'http://159.75.128.32:5000/api/category/update',
    categoryData,
    'PUT',
    'json'
  );

export const findCommoditiesRequest = (pageNum, pageSize) =>
  ajax(
    'http://159.75.128.32:5000/api/products/list',
    { pageNum, pageSize },
    'POST',
    'json'
  );

export const updateStatusByIdRequest = (id, status) =>
  ajax(
    `http://159.75.128.32:5000/api/products/updateStatus/${id}`,
    { status },
    'PUT',
    'json'
  );

export const updateCommodityByIdRequest = (id, commodityData) =>
  ajax(
    `http://159.75.128.32:5000/api/products/updateProduct/${id}`,
    commodityData,
    'PUT',
    'json'
  );

export const searchCommodityByDesc = (desc, pageNum, pageSize) =>
  ajax(
    `http://159.75.128.32:5000/api/products/searchByDesc/${desc}/${pageNum}/${pageSize}`,
    {},
    'GET'
  );

export const searchCommodityByName = (name, pageNum, pageSize) =>
  ajax(
    'http://159.75.128.32:5000/api/products/searchByName',
    { name, pageSize, pageNum },
    'GET'
  );

export const weatherRequest = (city) => {
  return new Promise((resolve, reject) => {
    const adcode = getCityAdcode(city);
    const url = `https://restapi.amap.com/v3/weather/weatherInfo?key=ffbf85ec1ac6132d3f1ba2feddd2c1dd&city=${adcode}`;
    jsonp(url, {}, (err, data) => {
      if (!err && data.status === '1') {
        const { weather, temperature, reporttime } = data.lives[0];
        resolve({ weather, temperature, reporttime });
      }
    });
  });
};
